<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth as JWT;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtAuth extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     *
     * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //指定jwt特定的模型
        //config(['jwt.user' => '\App\Models\User']);    //用于指定特定model
        //config(['auth.providers.users.model' => \App\Models\User::class]);//就是他们了

        try {
            if ($user = $this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            return response()->json(['code'=>402,'data'=>[],'msg'=>'未登录']);
        }catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $exception) {
            //token 放到黑名单列表了
            return response()->json(['code' => 490,'data'=>[],'msg'=>$exception->getMessage()]);
        }catch (JWTException $exception) {
            //token已过期 但是 没放入黑名单前。去刷新token 并返回去。
            try {
                $token = JWT::refresh(JWT::getToken());
                JWT::setToken($token);
                $request->user = JWT::authenticate($token);
                //return response()->json(['code'=>410,'data'=>['new_token'=>$token],'msg'=>'更新token']);
                $request->headers->set('Authorization','Bearer '.$token); // token被刷新之后，保证本次请求在controller中需要根据token调取登录用户信息能够执行成功
            } catch (JWTException $exception) {
                // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。
                return response()->json(['code'=>407,'data'=>[],'msg'=>$exception->getMessage()]);
            }
        } catch (TokenExpiredException $exception) {
            //不确定有没有用
            //token已过期 但是 没放入黑名单前。去刷新token 并返回去。
            try {
                $token = JWT::refresh(JWT::getToken());
                JWT::setToken($token);
                $request->user = JWT::authenticate($token);
                $request->headers->set('Authorization','Bearer '.$token); // token被刷新之后，保证本次请求在controller中需要根据token调取登录用户信息能够执行成功
            } catch (JWTException $exception) {
                // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。
                return response()->json(['code'=>407,'data'=>[],'msg'=>$exception->getMessage()]);
            }
        }

    }
}
